<?php

namespace app\admin\controller\auth;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 人员基准项模板设置管理
 *
 * @icon fa fa-circle-o
 */
class Asbitemplate extends Backend
{

    /**
     * Asbitemplate模型对象
     * @var \app\admin\model\auth\Asbitemplate
     */
    protected $model = null;
    protected $noNeedRight = ['benchmark_item_list'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\auth\Asbitemplate;
        $this->view->assign("benchmark", Db::table('b_salary_benchmark')->where('count_type',2)->select());
        $this->view->assign("benchmark_item", Db::table('b_salary_benchmark_item')->select());
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    $item_arr = [];
                    foreach ($params['item'] as $item){
                        $item_arr[] = [
                            'template_id'=>$this->model->getLastInsID(),
                            'salary_benchmark_id'=>$item['salary_benchmark_id'],
                            'salary_benchmark_item_id'=>$item['salary_benchmark_item_id'],
                        ];
                    }
                    Db::table('b_auth_asbi_template_item')->insertAll($item_arr);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['item'] = json_decode($params['item'],1);
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::table('b_auth_asbi_template_item')->where('template_id',$row->id)->delete();
                    $item_arr = [];
                    foreach ($params['item'] as $item){
                        $item_arr[] = [
                            'template_id'=>$row->id,
                            'salary_benchmark_id'=>$item['salary_benchmark_id'],
                            'salary_benchmark_item_id'=>$item['salary_benchmark_item_id'],
                        ];
                    }
                    Db::table('b_auth_asbi_template_item')->insertAll($item_arr);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
//        $row['salary_benchmark_item_name'] = Db::table('b_salary_benchmark_item')->where('id',$row['salary_benchmark_item_id'])->value('name');
        $item_arr = Db::table('b_auth_asbi_template_item')->field('salary_benchmark_id,salary_benchmark_item_id')->where('template_id',$row->id)->select();
        foreach ($item_arr as &$item){
            $item['salary_benchmark_item_name'] = Db::table('b_salary_benchmark_item')->where('id',$item['salary_benchmark_item_id'])->value('name');
        }
        $this->view->assign("item_arr", json_encode($item_arr));
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function benchmark_item_list()
    {
        $salary_benchmark_id = $this->request->post('salary_benchmark_id');
        $salary_benchmark_item_id = $this->request->post('salary_benchmark_item_id');
        $type = $this->request->post('type',1);
        if($type==2){
            $info = Db::table('b_salary_benchmark_item')->field('id,salary_benchmark_id,name')->where('id',$salary_benchmark_item_id)->find();
            $salary_benchmark_id = $info['salary_benchmark_id'];
        }
        $list = Db::table('b_salary_benchmark_item')->field('id,name')->where('salary_benchmark_id',$salary_benchmark_id)->select();
        $this->success('','',$list);
    }
    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                    Db::table('b_auth_asbi_template_item')->where('template_id',$v->id)->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
